package com.jinzecloud.reportapproval.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        CustomErrorResponse errorResponse = new CustomErrorResponse();

        errorResponse.setTimestamp(System.currentTimeMillis());
        errorResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        errorResponse.setError("Access Denied");
        errorResponse.setMessage("身份认证失败，拒绝访问");
        errorResponse.setPath(request.getRequestURI());

        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write(new ObjectMapper().writeValueAsString(errorResponse));
    }
}